package com.gxc.string;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;

/**
 * 基本计算器
 * 给你一个字符串表达式 s ，请你实现一个基本计算器来计算并返回它的值。
 *
 * 注意:不允许使用任何将字符串作为数学表达式计算的内置函数，比如 eval() 。
 */
public class Calculate2 {

    public static void main(String[] args) {
        System.out.println(calculate3("2147483647"));
    }

    public static int calculate(String s) {
        Deque<java.lang.Integer> ops = new LinkedList<java.lang.Integer>();
        ops.push(1);
        int sign = 1;

        int ret = 0;
        int n = s.length();
        int i = 0;
        while (i < n) {
            if (s.charAt(i) == ' ') {
                i++;
            } else if (s.charAt(i) == '+') {
                sign = ops.peek();
                i++;
            } else if (s.charAt(i) == '-') {
                sign = -ops.peek();
                i++;
            } else if (s.charAt(i) == '(') {
                ops.push(sign);
                i++;
            } else if (s.charAt(i) == ')') {
                ops.pop();
                i++;
            } else {
                long num = 0;
                while (i < n && Character.isDigit(s.charAt(i))) {
                    num = num * 10 + s.charAt(i) - '0';
                    i++;
                }
                ret += sign * num;
            }
        }
        return ret;
    }

    public int calculate2(String s) {
        // 存放所有的数字
        Deque<java.lang.Integer> nums = new ArrayDeque<>();
        // 为了防止第一个数为负数，先往 nums 加个 0
        nums.addLast(0);
        // 将所有的空格去掉
        s = s.replaceAll(" ", "");
        // 存放所有的操作，包括 +/-
        Deque<Character> ops = new ArrayDeque<>();
        int n = s.length();
        char[] cs = s.toCharArray();
        for (int i = 0; i < n; i++) {
            char c = cs[i];
            if (c == '(') {
                ops.addLast(c);
            } else if (c == ')') {
                // 计算到最近一个左括号为止
                while (!ops.isEmpty()) {
                    char op = ops.peekLast();
                    if (op != '(') {
                        calc(nums, ops);
                    } else {
                        ops.pollLast();
                        break;
                    }
                }
            } else {
                if (isNum(c)) {
                    int u = 0;
                    int j = i;
                    // 将从 i 位置开始后面的连续数字整体取出，加入 nums
                    while (j < n && isNum(cs[j])) u = u * 10 + (int)(cs[j++] - '0');
                    nums.addLast(u);
                    i = j - 1;
                } else {
                    if (i > 0 && (cs[i - 1] == '(' || cs[i - 1] == '+' || cs[i - 1] == '-')) {
                        nums.addLast(0);
                    }
                    // 有一个新操作要入栈时，先把栈内可以算的都算了
                    while (!ops.isEmpty() && ops.peekLast() != '(') calc(nums, ops);
                    ops.addLast(c);
                }
            }
        }
        while (!ops.isEmpty()) calc(nums, ops);
        return nums.peekLast();
    }
    void calc(Deque<java.lang.Integer> nums, Deque<Character> ops) {
        if (nums.isEmpty() || nums.size() < 2) return;
        if (ops.isEmpty()) return;
        int b = nums.pollLast(), a = nums.pollLast();
        char op = ops.pollLast();
        nums.addLast(op == '+' ? a + b : a - b);
    }
    boolean isNum(char c) {
        return Character.isDigit(c);
    }

    public static int calculate3(String s) {
        Deque<java.lang.Integer> nums = new LinkedList<>();
        nums.offerLast(0);
        Deque<Character> ops = new LinkedList<>();

        s = s.replaceAll(" ", "");
        int index = 0;
        while (index < s.length()) {
            char c = s.charAt(index);
            if (c == '(') {
                ops.offerLast(c);
            } else if (c == ')') {
                while (ops.peekLast() != '(') {
                    cal(nums, ops);
                }
                //去除（
                ops.pollLast();
            } else {
                if (isNum2(c)) {
                    int num = 0;
                    while (index < s.length() && isNum2(s.charAt(index))) {
                        num = num *10 + s.charAt(index) - '0';
                        index++;
                    }
                    index--;
                    nums.offerLast(num);
                } else {
                    if (index>0 && s.charAt(index-1) == '(') {
                        nums.offerLast(0);
                    }
                    while (!ops.isEmpty() && ops.peekLast() != '(') cal(nums, ops);
                    ops.offerLast(c);
                }
            }
            index++;
        }
        while (!ops.isEmpty()) cal(nums, ops);
        return nums.peekLast();
    }

    private static void cal(Deque<java.lang.Integer> nums, Deque<Character> ops) {
        if (nums.isEmpty() || nums.size()<2) return;
        if (ops.isEmpty()) return;

        int y = nums.pollLast(), x = nums.pollLast();
        Character c = ops.pollLast();
        int sum = c == '+'? x + y: x - y;
        nums.offerLast(sum);
    }

    private static boolean isNum2(char c) {
        return Character.isDigit(c);
    }

}
